namespace Digitalmes.Common.Workflows;

/// <summary>
/// 函数元数据工厂。
/// </summary>
internal static class WorkflowFunctionMetadataFactory
{
    /// <summary>
    /// 从注册了 <see cref="WorkflowFunctionAttribute"/> 的方法中提取函数元数据。
    /// </summary>
    /// <param name="instanceType">函数类型</param>
    /// <returns></returns>
    /// <exception cref="ArgumentException"></exception>
    public static IEnumerable<WorkflowFunctionMetadata> CreateFromType(Type instanceType)
    {
        MethodInfo[] methods = instanceType.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static);

        var functionMetadata = new List<WorkflowFunctionMetadata>();
        foreach (MethodInfo method in methods)
        {
            if (method.GetCustomAttribute<WorkflowFunctionAttribute>() is not null)
            {
                var parameters = method.GetParameters();
                functionMetadata.Add(new WorkflowFunctionMetadata(method.Name, method.GetParameters(), method.ReturnType));
            }
        }

        if (functionMetadata.Count == 0)
        {
            throw new ArgumentException($"The {instanceType} instance doesn't implement any [WorkflowFunction]-attributed methods.");
        }

        return functionMetadata;
    }
}
